比较两个ArrayList索引时的java IndexOutOfBoundsException
我正试图编写一个程序,在随机生成的ArrayList
20中找到最长的数字序列,然后在括号中标记该序列。然而,当我试图比较for循环中ArrayList
的两个索引值时,会出现IndexOutOfBoundsException
,我不确定问题出在哪里
ArrayList<Integer> dieTosses = new ArrayList<Integer>();
for(int i = 0; i < 20; i++)
{
dieTosses.add((int) (Math.random()*6)+1);
}
int longestRun = 1;
int runTracker = 1;
for(int i = 0; i < dieTosses.size(); i++) //The problem occurs here
{
if(dieTosses.get(i) == dieTosses.get(i+1))
{
longestRun++;
}
else if(longestRun > runTracker);
longestRun = runTracker;
}
System.out.println(dieTosses);
System.out.println(longestRun);
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 20, Size: 20
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at DieTossing.DieTosser.main(DieTosser.java:18)
# 1 楼答案
根据我观察到的情况,可能是在我到达迪托塞斯时。size(),您正在尝试调用dieTosses。获得(i+1)导致其超出范围,更改
for(int i = 0; i < dieTosses.size(); i++)
到
# 2 楼答案
你有问题吗
因为在for循环(对于值19)的最后一次迭代中,您试图访问位于
dieTosses.get(i+1)
的位置20。这不存在,因为它们是通过0-19索引的试试这个
或者
你喜欢哪个版本